package camid.services.cloudmanager;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import camid.services.nameservice.EntityMetadata;

public class RoundRobinLoadBalancingStrategy implements LoadBalancingStrategy {

	private Map<String, Integer> entityDefinitionCounters;
	
	public RoundRobinLoadBalancingStrategy()
	{
		entityDefinitionCounters = new HashMap<String,Integer> ();
	}
	
	@Override
	public String selectNode(EntityMetadata metadata, List<String> nodeIds) {
		
		if(nodeIds.size() == 0)
			return null;
		
		String chosenNodeId = null;
		if(!entityDefinitionCounters.containsKey(metadata.getEntityType()))
		{
			entityDefinitionCounters.put(metadata.getEntityType(), 0);
			chosenNodeId = nodeIds.get(0);
		}
		else
		{
			Integer counter = (entityDefinitionCounters.get(
					metadata.getEntityType()) + 1) % nodeIds.size();
			chosenNodeId = nodeIds.get(counter);
			entityDefinitionCounters.put(metadata.getEntityType(), counter);
		}
		
		return chosenNodeId;
	}

	@Override
	public String reselectNode(EntityMetadata metadata, List<String> nodeIds,
			String oldNodeId) 
	{	
		String chosenNodeId = selectNode(metadata, nodeIds);
		return chosenNodeId;
	}

}
